package com.example.word.ui.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.word.bean.StudyPlan;
import com.example.word.bean.User;
import com.example.word.ui.activity.BrowseActivity;
import com.example.word.ui.activity.CollectActivity;
import com.example.word.ui.activity.ManageActivity;
import com.example.word.MyApplication;
import com.example.dict.R;
import com.example.word.ui.activity.LoginActivity;
import com.example.word.ui.activity.PasswordActivity;
import com.example.word.ui.activity.PersonActivity;
import com.example.word.ui.activity.StudyPlanActivity;
import com.example.word.ui.activity.WordManageActivity;
import com.example.word.ui.activity.WordReviewActivity;
import com.example.word.ui.activity.WxActivity;
import com.example.word.util.CommonUtils;
import com.example.word.util.HttpUtils;
import com.example.word.util.MessageUtils;
import com.example.word.util.Response;
import com.example.word.util.SPUtils;
import com.example.word.util.StringUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * 个人中心Fragment
 */
public class UserFragment extends Fragment {
    private Activity mActivity;
    private LinearLayout llPerson;
    private LinearLayout llSecurity;
    private LinearLayout manage, wordManage;
    private Button btnLogout;
    private ImageView bt_review;
    private ImageView bt_studyPlan;
    private ImageView bt_studyLog;
    private ImageView bt_collect;
    private ImageView bt_kehu;
    private TextView author, bt_reviewText, bt_studyPlanText, bt_studyLogText, bt_collectText, bt_kehuText;
    private TextView userWelcome;
    private TableLayout taborder;
    private RelativeLayout taborder2;
    private String account;
    private LinearLayout update;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mActivity = (Activity) context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_user, container, false);
        llPerson = view.findViewById(R.id.person);
        llSecurity = view.findViewById(R.id.security);
        manage = view.findViewById(R.id.manage);
        wordManage = view.findViewById(R.id.wordManage);
        update = view.findViewById(R.id.update);
        btnLogout = view.findViewById(R.id.logout);
        bt_studyPlan = view.findViewById(R.id.bt_studyPlan);
        bt_studyLog = view.findViewById(R.id.bt_studyLog);
        bt_review = view.findViewById(R.id.bt_review);
        bt_collect = view.findViewById(R.id.bt_collect);
        bt_kehu = view.findViewById(R.id.bt_kehu);
        bt_studyPlanText = view.findViewById(R.id.bt_studyPlanText);
        bt_studyLogText = view.findViewById(R.id.bt_studyLogText);
        bt_reviewText = view.findViewById(R.id.bt_reviewText);
        bt_collectText = view.findViewById(R.id.bt_collectText);
        bt_kehuText = view.findViewById(R.id.bt_kehuText);
        taborder = view.findViewById(R.id.taborder);
        taborder2 = view.findViewById(R.id.taborder2);
        author = view.findViewById(R.id.author);
        userWelcome = view.findViewById(R.id.userWelcome);

        initView();
        return view;
    }

    private void initView() {
        Boolean isAdmin = (Boolean) SPUtils.get(mActivity, SPUtils.IS_ADMIN, false);
        account = (String) SPUtils.get(mActivity, SPUtils.ACCOUNT, "");
//        taborder.setVisibility(isAdmin ? View.GONE : View.VISIBLE);
//        taborder2.setVisibility(isAdmin ? View.GONE : View.VISIBLE);
        manage.setVisibility(isAdmin ? View.VISIBLE : View.GONE);
        wordManage.setVisibility(isAdmin ? View.VISIBLE : View.GONE);
        loadData();
        //支持作者
        author.setOnClickListener(view -> {
            //跳转页面
            Intent intent = new Intent(mActivity, WxActivity.class);
            startActivity(intent);
        });
        //学习计划
        bt_studyPlan.setOnClickListener(view -> {
            //跳转页面
            Intent intent = new Intent(mActivity, StudyPlanActivity.class);
            startActivity(intent);
        });
        //学习计划
        bt_studyPlanText.setOnClickListener(view -> {
            //跳转页面
            Intent intent = new Intent(mActivity, StudyPlanActivity.class);
            startActivity(intent);
        });

        //学习记录
        bt_studyLog.setOnClickListener(view -> {
            //跳转页面
            Intent intent = new Intent(mActivity, BrowseActivity.class);
            startActivity(intent);
        });
        bt_studyLogText.setOnClickListener(view -> {
            //跳转页面
            Intent intent = new Intent(mActivity, BrowseActivity.class);
            startActivity(intent);
        });

        //复习单词
        bt_review.setOnClickListener(view -> {
            Intent intent = new Intent(mActivity, WordReviewActivity.class);
            startActivity(intent);
        });
        bt_reviewText.setOnClickListener(view -> {
            Intent intent = new Intent(mActivity, WordReviewActivity.class);
            startActivity(intent);
        });

        //收藏记录
        bt_collect.setOnClickListener(view -> {
            //跳转页面
            Intent intent = new Intent(mActivity, CollectActivity.class);
            startActivity(intent);
        });
        bt_collectText.setOnClickListener(view -> {
            //跳转页面
            Intent intent = new Intent(mActivity, CollectActivity.class);
            startActivity(intent);
        });
        //联系客服
        bt_kehu.setOnClickListener(view -> {
            //跳转到客服
            AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
            builder.setIcon(R.drawable.a1);//设置图标
            builder.setTitle("球球单词");//设置对话框的标题
            builder.setMessage("即将跳转到在线客服，是否确认？");
            builder.setPositiveButton("确定", (dialog, which) -> {
                        ProgressDialog dialog3 = new ProgressDialog(mActivity);
                        dialog3.setMessage("正在连接客服···");
                        dialog3.show();
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Toast.makeText(mActivity, "如无法联系，请添加好友后再试!", Toast.LENGTH_LONG).show();
                                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("mqqapi://card/show_pslcard?src_type=internal&source=sharecard&version=1&uin=1632957243")));//跳转到QQ资料
                                } catch (Exception e) {
                                    Toast.makeText(mActivity, "请安装最新版QQ后使用此功能!", Toast.LENGTH_LONG).show();
                                }
                                dialog3.dismiss();
                            }
                        }, 505);

                    }
            );
            builder.setNegativeButton("取消", (dialog, which) -> {
            });
            AlertDialog a = builder.create();
            a.show();

        });
        bt_kehuText.setOnClickListener(view -> {
            //跳转到客服
            AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
            builder.setIcon(R.drawable.a1);//设置图标
            builder.setTitle("球球单词");//设置对话框的标题
            builder.setMessage("即将跳转到在线客服，是否确认？");
            builder.setPositiveButton("确定", (dialog, which) -> {
                        ProgressDialog dialog3 = new ProgressDialog(mActivity);
                        dialog3.setMessage("正在连接客服···");
                        dialog3.show();
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Toast.makeText(mActivity, "如无法联系，请添加好友后再试!", Toast.LENGTH_LONG).show();
                                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("mqqapi://card/show_pslcard?src_type=internal&source=sharecard&version=1&uin=1632957243")));//跳转到QQ资料
                                } catch (Exception e) {
                                    Toast.makeText(mActivity, "请安装最新版QQ后使用此功能!", Toast.LENGTH_LONG).show();
                                }
                                dialog3.dismiss();
                            }
                        }, 505);

                    }
            );
            builder.setNegativeButton("取消", (dialog, which) -> {
            });
            AlertDialog a = builder.create();
            a.show();

        });
        //个人信息
        llPerson.setOnClickListener(v -> {
            //跳转页面
            Intent intent = new Intent(mActivity, PersonActivity.class);
            startActivity(intent);
        });
        //用户管理
        manage.setOnClickListener(v -> {
            //跳转页面
            Intent intent = new Intent(mActivity, ManageActivity.class);
            startActivity(intent);
        });
        //单词管理
        wordManage.setOnClickListener(v -> {
            //跳转页面
            Intent intent = new Intent(mActivity, WordManageActivity.class);
            startActivity(intent);
        });
        //账号安全
        llSecurity.setOnClickListener(v -> {
            //跳转页面
            Intent intent = new Intent(mActivity, PasswordActivity.class);
            startActivity(intent);
        });
        //版本更新
        update.setOnClickListener(view -> {
            ProgressDialog dialog = new ProgressDialog(mActivity);
            dialog.setMessage("正在检查版本信息···");
            dialog.show();
            new Handler().postDelayed(() -> HttpUtils.sendGetRequest("/getVersion", new HashMap<>(), mActivity, Integer.class, response -> {
                if (response.getData() > HttpUtils.version) {
                    MessageUtils.show("发现新版本，请前往下载", mActivity);

                    Uri uri = Uri.parse(CommonUtils.appDownloadUrl);
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(uri, "text/html");
                    startActivity(intent);
                } else {
                    MessageUtils.show("当前已是最新版本", mActivity);
                }
                dialog.dismiss();
            }), 1000);
        });

        //退出登录
        btnLogout.setOnClickListener(v -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
            builder.setIcon(R.drawable.a1);//设置图标
            builder.setTitle("球球单词");//设置对话框的标题
            builder.setMessage("提示：退出后将清空您的登录信息");
            Map<String, String> requestParam = new HashMap<>();
            requestParam.put("userAccount", account);
            builder.setPositiveButton("确定", (dialog, which) -> HttpUtils.sendGetRequest("/userLogout", requestParam, mActivity, Object.class, response -> {
                MyApplication.Instance.getMainActivity().finish();
                SPUtils.remove(mActivity, SPUtils.IS_ADMIN);
                SPUtils.remove(mActivity, SPUtils.ACCOUNT);
                startActivity(new Intent(mActivity, LoginActivity.class));
            }));
            builder.setNegativeButton("取消", (dialog, which) -> {
            });
            AlertDialog a = builder.create();
            a.show();
        });
    }

    /**
     * 加载数据
     */
    public void loadData(Activity... activities) {
        if (StringUtils.isEmpty(account)) {
            return;
        }
        // 获取当前用户信息
        HttpUtils.sendGetRequest("/getUserByAccount", new HashMap<>(), mActivity, User.class, (HttpUtils.ApiCallback<User>) response -> {
            // 处理请求成功的情况
            User user = (User) response.getData();
            userWelcome.setText("欢迎你！" + user.getNickName() + " (" + user.getAccount() + ")");
        });

    }

    public void callPhone(String str) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + str);
        intent.setData(data);
        startActivity(intent);
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData();
    }

    public void setColor() {
        // 设置按钮主题
        if (!com.example.word.ui.activity.MainActivity.colorChange) {
            btnLogout.setBackground(getResources().getDrawable(R.drawable.btn_border_fill));
        } else {
            btnLogout.setBackground(getResources().getDrawable(R.drawable.btn_border_fill_my_color));
        }
    }
}
